//
//  ViewController.m
//  runtime
//
//  Created by huihu long on 12-5-17.
//  Copyright (c) 2012年 netease. All rights reserved.
//
#import <objc/runtime.h>
#import "ViewController.h"

@interface OtherObject : NSObject
- (void)forwardImp;
@end

@implementation OtherObject

- (void)forwardImp {
    NSLog(@"OtherObject:forwardImp called");    
}

@end

@implementation ViewController

void dynamicMethodIMP(id self, SEL _cmd) {
    
}

//如果没有定义某个selector，则这个方法会被调用，返回YES表示你提供了一个动态方法，否则
//会进入forward阶段
+ (BOOL)resolveInstanceMethod:(SEL)sel {
    NSLog(@"resolveInstanceMethod:%@",NSStringFromSelector(sel));
    if (sel==@selector(abc:)) {
        class_addMethod([self class],sel,(IMP)dynamicMethodIMP,"v@:");
        return YES;
    }
    return [super resolveInstanceMethod:sel];
}

    static OtherObject *obj = nil;

- (id)forwardingTargetForSelector:(SEL)aSelector {
    NSLog(@"forwardingTargetForSelector:%@",NSStringFromSelector(aSelector));  
    if (obj==nil) {
        obj = [[OtherObject alloc] init];
    }
    return obj;
}

- (void)forwardInvocation:(NSInvocation *)anInvocation {
    NSLog(@"forwardInvocation:%@",NSStringFromSelector(anInvocation.selector));  
    [anInvocation invoke];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self performSelector:@selector(abc:)];
    [self performSelector:@selector(forwardImp)];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end
